#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Wave Relay
# Copyright (C) 2010 Yakovlev Vladimir [nvbn.rm@gmail.com]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from PyQt4 import QtGui
import json

class Song(QtGui.QTreeWidgetItem):
    """Class contain widget of song in list"""
    artist = None
    name = None
    album = None
    song = None
    _song_url = None
    _song_file = None
    _urlnum = 0

    def __init__(self, song = None):
        """Create widget and set values

        Keyword arguments:
        song -- pylast.Song

        Returns: None

        """
        if song:
            self.artist = song.artist.get_name()
            self.name = song.get_name()
            try:
                self.album = song.get_album().get_name()
            except AttributeError:
                pass
            self.song = song
        QtGui.QTreeWidgetItem.__init__(self)

    def get_url(self, vk, refresh = False):
        """Return vk url for song

        Keyword arguments:
        vk -- Vk
        refresh -- Bolean

        Returns: Url

        """
        if self._song_url and not refresh:
            return(self._song_url)
        else:
            try:
                self._song_url = vk.find_song_urls(self.artist + ' - ' + self.name)[self._urlnum].path
            except:
                self._song_url = vk.find_song_urls(self.artist + ' - ' + self.name)[0].path
                self._urlnum = 0
            self._urlnum += 1
            return(self._song_url)

    def get_song(self, ls):
        """Get songs

        Keyword arguments:
        ls -- LastSearch

        Returns: Song

        """
        if self.song == None:
            self.song = ls.searchTrack('%s - %s' % (self.artist, self.name))[0]
            return(self.song)
        else:
            return(self.song)

    @classmethod
    def load(cls, **kwargs):
        """Load song value for specified args"""
        cls = Song()
        for arg in kwargs:
            setattr(cls, arg, kwargs[arg])
        return(cls)

    def save(self):
        """Return array with song values is specified format"""
        get = lambda *args: [(arg, getattr(self, arg, None),) for arg in args]
        return(get('name', 'artist', '_song_url'))







class Artist(QtGui.QTreeWidgetItem):
    """Class contain artist widget"""
    name = None
    artist = None

    def __init__(self, artist):
        """Create widget and set params

        Keyword arguments:
        artist -- pylast.Artist

        Returns: None

        """
        self.artist = artist
        self.name = artist.get_name()
        QtGui.QTreeWidgetItem.__init__(self)

    def get_songs(self):
        """Iterator returns artist songs"""
        for song in self.artist.get_top_tracks():
            yield(song[0])

    def get_albums(self):
        """Iterator returns artist albums"""
        for album in self.artist.get_top_albums():
            yield(album[0])



class Album(QtGui.QTreeWidgetItem):
    """Class contain album widget"""
    artist = None
    album = None
    name = None

    def __init__(self, album):
        """Create album widget and set values

        Keyword arguments:
        album -- pylast.ALbum

        Returns: None

        """
        self.album = album
        self.artist = album.artist.get_name()
        self.name = album.get_name()
        QtGui.QTreeWidgetItem.__init__(self)

    def get_songs(self):
        """Iterator returns songs"""
        for song in self.album.get_tracks():
            yield(song)

class Genre(QtGui.QTreeWidgetItem):
    """Class contain genre widget"""
    genre = None
    name = None

    def __init__(self, genre):
        """Create genre widget and set values

        Keyword arguments:
        genre -- pylast.Tag

        Returns: None

        """
        self.genre = genre
        self.name = genre.get_name()
        QtGui.QTreeWidgetItem.__init__(self)

    def get_songs(self):
        """Iterator returns songs with tag"""
        for song in self.genre.get_top_tracks():
            yield(song[0])

    def get_artist(self):
        """Iterator returns artist with tag"""
        for artist in self.genre.get_top_artists():
            yield(artist[0])


class Playlist:
    """Playlist widget and array container"""
    playlist = []
    widget = None

    def __init__(self, widget):
        """Init class

        Keyword arguments:
        widget -- QtGui.QTreeWidget

        Returns: None

        """
        self.widget = widget
        self.icon = QtGui.QIcon()
        self.icon.addPixmap(QtGui.QPixmap("spacer.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)

    def append(self, song):
        """Add song to playlist

        Keyword arguments:
        song -- Song

        Returns: None

        """
        self.playlist.append(song)
        song.setIcon(0, self.icon)
        song.setText(0, song.artist)
        song.setText(1, song.name)
        #song.setText(2, song.album)
        self.widget.addTopLevelItem(song)

    def remove(self, song):
        """Remove song from playlist

        Keyword arguments:
        song -- Song

        Returns: None

        """
        del self.playlist[self.playlist.index(song)]
        self.widget.removeItemWidget(song)

    def clear(self):
        """Clear list"""
        self.widget.clear()
        self.playlist = []

    def get(self, id):
        """Get song by id from playlist

        Keyword arguments:
        id -- int

        Returns: Song

        """
        return(self.playlist[id])

    def get_id(self, song):
        """Get id by song from playlist

        Keyword arguments:
        id -- int

        Returns: Song

        """
        return(self.playlist.index(song))

    def save(self, file = None):
        """Save playlist

        Keyword arguments:
        file -- String -- path

        Returns: Boolean

        """
        file = open(file, 'w')
        file.write(json.dumps([song.save() for song in self.playlist]))
        file.close()
        return(True)

    def load(self, file = None):
        """Load playlist

        Keyword arguments:
        file -- String -- path

        Returns: Boolean

        """
        file = open(file, 'r')
        data = json.loads(file.read())
        file.close()
        self.clear()
        for song in data:
            args = {}
            for arg in song:
                args[arg[0]] = arg[1]
            self.append(Song.load(**args))

class Search:
    """Search array and widget class"""
    TYPES = {
        'artist': 0,
        'album': 1,
        'song': 2,
        'genre': 3
    }

    type = None
    search = []
    widget = None

    def __init__(self, widget):
        """Init class

        Keyword arguments:
        widget -- QtGui.QTreeWidget

        Returns: None

        """
        self.widget = widget

    def append(self, item, type):
        """Add item to search list

        Keyword arguments:
        item -- Song, Artist, Song, Album
        type -- int of TYPES

        Returns: None

        """
        self.type = type
        self.search.append(item)
        if type in (self.TYPES['artist'], self.TYPES['genre']):
            item.setText(0, item.name)
        elif type in (self.TYPES['album'], self.TYPES['song']):
            item.setText(0, item.artist + ' - ' + item.name)
        self.widget.addTopLevelItem(item)

    def clear(self):
        """Clear list"""
        self.widget.clear()
        self.search = []

